//
//  ConfirmationViewController.m
//  PlayerWorld
//
//  Created by 1 on 16/6/14.
//  Copyright © 2016年 刘成. All rights reserved.
//
#define UISCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width
#define UISCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define Cell1 @"cell1"
#define Cell2 @"cell2"
#define Cell3 @"cell3"

#import "ConfirmationViewController.h"
#import "ConfirmationTableViewCell.h"
#import "Confirmation1TableViewCell.h"
#import "Confirmation2TableViewCell.h"
#import "G_P_Object.h"
#import "ConfirmationBetViewController.h"
#import "LZFoldButton.h"
#import "UIKit+AFNetworking.h"
#import "HighLightsModel.h"
#import "AddChaseViewController.h"
@interface ConfirmationViewController ()<LZFoldButtonDelegate, UITextFieldDelegate>
{
    LZFoldButton *lz;
    HighLightsModel *model;
    NSInteger _value;
    CGFloat _floatNum;
    CGFloat _valueFloat;
}


@end

@implementation ConfirmationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self obtainDataXinXi];
    model = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"]];
    _floatNum = [model.U_RebateB floatValue] / [model.U_RebateA floatValue];
//    _array = [NSMutableArray array];
//    for (NSString *str in [_listArr firstObject]) {
//        for (NSString *str1 in [_listArr objectAtIndex:1]) {
//            for (NSString *str2 in [_listArr objectAtIndex:2]) {
//                for (NSString *str3 in [_listArr objectAtIndex:3]) {
//                    for (NSString *str4 in [_listArr objectAtIndex:4]) {
//                        [_array addObject:[NSString stringWithFormat:@"%@,%@,%@,%@,%@",str,str1,str2,str3,str4]];
//                    }
//                }
//            }
//        }
//    }
    _value = 1;
    self.G_P_Model.G_P_Bonus = [[self.G_P_Model.G_P_Bonus componentsSeparatedByString:@","] lastObject];
    self.G_P_Model.G_P_AmountStep = [[[[self.G_P_Model.G_P_AmountStep componentsSeparatedByString:@","] lastObject] componentsSeparatedByString:@"="] firstObject];
    self.view.backgroundColor = [UIColor redColor];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
    self.title = @"确认投注";

    if ([[NSUserDefaults standardUserDefaults] floatForKey:@"yjfl"]) {
        _valueFloat = [[NSUserDefaults standardUserDefaults] floatForKey:@"yjfl"];
    }
    else{
        _valueFloat = 1.0;
    }
    // highlightstableView
    confirmationtableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, UISCREEN_HEIGHT) style:UITableViewStylePlain];
    confirmationtableView.dataSource = self;
    confirmationtableView.delegate = self;
    [confirmationtableView registerClass:[ConfirmationTableViewCell class] forCellReuseIdentifier:Cell1];
    [confirmationtableView registerNib:[UINib nibWithNibName:@"Confirmation1TableViewCell" bundle:nil]  forCellReuseIdentifier:Cell2];
    [confirmationtableView registerNib:[UINib nibWithNibName:@"Confirmation2TableViewCell" bundle:nil]  forCellReuseIdentifier:Cell3];

    confirmationtableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:confirmationtableView];

    UILabel *ConfirmationLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, 30)];
    ConfirmationLabel.backgroundColor = [UIColor whiteColor];
    ConfirmationLabel.text = [NSString stringWithFormat:@"第%@期",self.Issue];
    ConfirmationLabel.textAlignment = NSTextAlignmentCenter;
    ConfirmationLabel.font = [UIFont systemFontOfSize:14];
    confirmationtableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30)];
    [confirmationtableView.tableHeaderView addSubview:ConfirmationLabel];
    UIView *tapView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30+20*3+50+80*1+11)];
    tapView.backgroundColor = [UIColor clearColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEditingAction:)];
    [tapView addGestureRecognizer:tap];
    [self.view addSubview:tapView];
    [self personalLZFoldButton];
}
- (void)endEditingAction:(UITapGestureRecognizer *)tap
{
    UITextField *textField = [self.view viewWithTag:1000];
    [textField resignFirstResponder];
}
-(void)personalLZFoldButton
{
    NSArray *arr = @[@"元",@"角",@"分",@"厘"];

    lz = [[LZFoldButton alloc]initWithFrame:CGRectMake(UISCREEN_WIDTH-50-10, 30+20*3+50+80*1+11, 50, 30) dataArray:arr];
    lz.lzDelegate = self;
    lz.lzFontSize = 12;
    lz.lzHeight = 90;
    lz.lzButtonType = 1;

    if (_valueFloat > 0.2) {
        [lz LZSetTitle:@"元" forState:UIControlStateNormal];
    }
    if (_valueFloat < 0.9 && _valueFloat > 0.09) {
        [lz LZSetTitle:@"角" forState:UIControlStateNormal];
    }
    if (_valueFloat < 0.09 && _valueFloat > 0.002) {
        [lz LZSetTitle:@"分" forState:UIControlStateNormal];
    }
    if (_valueFloat < 0.009) {
        [lz LZSetTitle:@"厘" forState:UIControlStateNormal];
    }
    [lz LZSetImage:[UIImage imageNamed:@"icon_select_arrow"] forState:UIControlStateNormal];
    [lz LZSetImage:[UIImage imageNamed:@"icon_select_arrow"] forState:UIControlStateSelected];
    [lz LZSetTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [confirmationtableView addSubview:lz];
}

-(void)LZFoldButton:(LZFoldButton*)foldButton didSelectObject:(id)obj {
    if ([obj isEqualToString:@"元"]) {
        _valueFloat = 1.0;
    }
    if ([obj isEqualToString:@"角"]) {
        _valueFloat = 0.1;
    }
    if ([obj isEqualToString:@"分"]) {
        _valueFloat = 0.01;
    }
    if ([obj isEqualToString:@"厘"]) {
        _valueFloat = 0.001;
    }
    [confirmationtableView reloadData];
}

// 单元格高度
- (CGFloat)tableView:(UITableView *)atableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 50;
    }else if (indexPath.section == 1){
        return 80;

    }else{
        return 164;
    }
 }

//设置表视图中的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    } else if (section == 1){
        return 1;
    } else {
        return 1;
    }
}

//设置表视图中的section（分组）数,默认为1
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
// 设置header的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

//设置单元格中的数据
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        ConfirmationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell1];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor blackColor];
        for (NSInteger i = 0; i < 3; i++) {
            UIButton *btn = (UIButton *)[cell.contentView viewWithTag:10+i];
            [btn addTarget:self action:@selector(chooseTheBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        }
        return cell;
    }else if (indexPath.section == 1){

        Confirmation1TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell2];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.lotteryNumbersLabel.text = self.string;
        cell.exampleLabel.text = self.G_P_Model.G_P_Name;
        return cell;

    }else{

        Confirmation2TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell3];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.confirmatonSlider addTarget:self action:@selector(confirmatonSliderAction:) forControlEvents:UIControlEventValueChanged];
        cell.confirmation1TextField.tag = 1000;
        cell.confirmation1TextField.delegate = self;
#warning -------v
        cell.confirmatonSlider.value = [[NSUserDefaults standardUserDefaults] floatForKey:@"floatNum"];
        
        [cell.confirmation1Button addTarget:self action:@selector(addAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contirmation2Button addTarget:self action:@selector(secSliderAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.confirmButton addTarget:self action:@selector(confirmButtonAction:) forControlEvents:UIControlEventTouchUpInside];

        cell.confirmation1TextField.text = [NSString stringWithFormat:@"%ld",(long)_value];
        cell.moneyLabel.text = [NSString stringWithFormat:@"%.4f元",self.money*_value*_valueFloat];
        NSLog(@"kdkskjfkkj %f",self.money*_value*_valueFloat);
        cell.numLabel.text = [NSString stringWithFormat:@"%ld注 %ld倍",(long)self.money,(long)_value];
        [confirmationtableView addSubview:lz];
        
#warning --------v
        NSInteger num = 1700 + [[NSUserDefaults standardUserDefaults] floatForKey:@"floatNum"]*[model.U_RebateA floatValue] * 20;
        cell.countLabel.text = [NSString stringWithFormat:@"%ld",(long)num];
#warning -----------v
        CGFloat fnum = [model.U_RebateA floatValue] - [model.U_RebateA floatValue]*[[NSUserDefaults standardUserDefaults] floatForKey:@"floatNum"];
        cell.pctLabel.text = [NSString stringWithFormat:@"%.2f",fnum];
//        NSLog(@",,,,,,,,,,%f",[self.G_P_Model.G_P_AmountStep floatValue]);
#warning ---------v
        CGFloat mon = ([self.G_P_Model.G_P_Bonus floatValue]+[model.U_RebateA floatValue]*[self.G_P_Model.G_P_AmountStep floatValue]*[[NSUserDefaults standardUserDefaults] floatForKey:@"floatNum"])*_value*_valueFloat;
        cell.currentMoneyLabel.text = [NSString stringWithFormat:@"当前奖金%.4f元",mon];
        [cell.addChaseBtn addTarget:self action:@selector(addChaseAction:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}
- (void)addChaseAction:(UIButton *)btn
{
    CGFloat fnum =[model.U_RebateA floatValue] - [model.U_RebateA floatValue]*_floatNum;
    AddChaseViewController *viewC = [[AddChaseViewController alloc] init];
    viewC.Issue = self.Issue;
    viewC.G_P_Id = self.G_P_Model.G_P_Id;
    viewC.Rebate = [NSString stringWithFormat:@"%.2f",fnum];
    viewC.G_N_Id = self.G_N_Id;
    viewC.money = [NSString stringWithFormat:@"%ld",self.money];
    viewC.codeString = self.string;
    viewC.Multiple = [NSString stringWithFormat:@"%f",_valueFloat*_value];
    [self.navigationController pushViewController:viewC animated:YES];
}
-(void)secSliderAction:(UIButton *)sender{
    if (_value == 100) return;
    _value ++;
    [confirmationtableView reloadData];
}

-(void)addAction:(UIButton *)sender{
    if (_value == 1) return;
    _value --;
    [confirmationtableView reloadData];
}

-(void)confirmButtonAction:(UIButton *)sender{
    [self obtainData];
}


-(void)confirmatonSliderAction:(UISlider *)slider{
    _floatNum = slider.value;
#warning -------v
    [[NSUserDefaults standardUserDefaults] setFloat:_floatNum forKey:@"floatNum"];
    
    [confirmationtableView reloadData];
}

//集合按钮点击事件
- (void)chooseTheBtnClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
//    if (sender.tag == 10) {
//        NSLog(@"123");
//    } else if (sender.tag == 11) {
//        NSLog(@"456");
//    }else {
//        NSLog(@"789");
//    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    _value = [textField.text integerValue];
}
-(void)obtainData
{
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //服务器给的域名
    NSString *domainStr = @"http://666.lefun6.com/";
    
    //创建一个可变字典
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:@"Game" forKey:@"Model"];
    [parametersDic setObject:@"AddBuy" forKey:@"Action"];
    [parametersDic setObject:self.G_N_Id forKey:@"Id"];
    [parametersDic setObject:self.Issue forKey:@"Issue"];
    [parametersDic setObject:@"0" forKey:@"IsChaseCode"];
    [parametersDic setObject:[NSString stringWithFormat:@"%f",_valueFloat*_value] forKey:@"Multiple"];
    [parametersDic setObject:@"" forKey:@"BuyChase"];
    CGFloat fnum =[model.U_RebateA floatValue] - [model.U_RebateA floatValue]*_floatNum;
    [parametersDic setObject:[NSString stringWithFormat:@"%.2f",fnum] forKey:@"Rebate"];
    [parametersDic setObject:[NSString stringWithFormat:@"%.4f",self.money*_value*_valueFloat] forKey:@"TheTotalAmount"];

    NSString *codeStr = self.string;
    NSString *str = [NSString stringWithFormat:@"%@+%@+%ld",self.G_P_Model.G_P_Id,codeStr,_money];
    [parametersDic setObject:str forKey:@"BuyCode"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
    [manager POST:domainStr parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 解析成功隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([[dic objectForKey:@"msg"] isEqualToString:@"投注成功"]) {
            ConfirmationBetViewController *cbVC= [[ConfirmationBetViewController alloc] init];
            cbVC.money = [NSString stringWithFormat:@"%.4f",self.money*_value*_valueFloat];
            [self.navigationController pushViewController:cbVC animated:YES];
        }
        else{
            UIAlertController *alerView = [UIAlertController alertControllerWithTitle:@"提示信息" message:[dic objectForKey:@"msg"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alerView addAction:action];
            [self presentViewController:alerView animated:YES completion:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
    }];
    
}
-(void)obtainDataXinXi
{
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //服务器给的域名
    NSString *domainStr = @"http://666.lefun6.com/";
    
    //创建一个可变字典
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:@"User" forKey:@"Model"];
    [parametersDic setObject:@"GetUserInfo" forKey:@"Action"];
    [parametersDic setObject:@"yes" forKey:@"r"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
    [manager POST:domainStr parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 解析成功隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        model = [[HighLightsModel alloc]init];
        [model setValuesForKeysWithDictionary:[dic objectForKey:@"userinfo"]];
        
        // 存储到NSUserDefaults
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"uid"];
        [confirmationtableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
    }];
    
}

@end
